//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from 'react';
import { createRoot } from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import { Provider } from 'mobx-react';
import '@/styles/global.less';
import { renderRoutes } from 'react-router-config';
import routes from './routes';
import stores from '@/stores';
import zhCN from 'antd/lib/locale/zh_CN';
import { message, ConfigProvider } from 'antd';
import { ErrorBoundary } from '@/components/ErrorBoundary';
import 'moment/dist/locale/zh-cn';
import 'remirror/styles/all.css';
import '@/components/Editor/editor.less';
import { list_server, report_error } from './api/client_cfg';
import { conn_grpc_server, get_conn_server_addr } from './api/main';

const App = () => {
  const [hasConn, setHasConn] = useState(false);

  const getDefaultServer = async () => {
    const res = await list_server(false);
    const connServAddr = await get_conn_server_addr();
    for (const server of res.server_list) {
      if (!server.addr.includes(":")) {
        server.addr += ":5000";
      }
      if (server.addr.replace("http://", "") == connServAddr.replace("http://", "").replace("/", "")) {
        return server.addr;
      }
    }
    for (const item of res.server_list) {
      if (item.default_server) {
        return item.addr;
      }
    };
    return "";
  };

  const connDefaultServer = async () => {
    const addr = await getDefaultServer();
    if (addr == "") {
      message.error("服务器地址为空");
      return false;
    }
    const res = await conn_grpc_server(addr);
    if (res == false) {
      message.error("连接服务器失败");
      return false;
    }
    return true;
  };

  const init = async () => {
    await stores.appStore.loadVendorCfg();

    const success = await connDefaultServer();
    if (success) {
      stores.appStore.loadClientCfg();
      stores.localRepoStore.init();
    }
    if (success && stores.userStore.sessionId !== '') {
      stores.projectStore.initLoadProjectList();
      stores.orgStore.initLoadOrgList().then(() => {
        stores.orgStore.setCurOrgId("");
      });
    }
    setHasConn(true);
  };

  useEffect(() => {
    init();

    const unListenList = stores.noticeStore.initListen();

    return () => {
      unListenList.then(unListens => {
        for (const unListen of unListens) {
          unListen();
        }
      })
    };
  }, []);

  useEffect(() => {
    if (hasConn && stores.appStore.clientCfg == undefined) {
      let count = 1;
      const t = setInterval(() => {
        count += 1;
        if (count > 3) {
          clearInterval(t);
        } else {
          stores.appStore.loadClientCfg().then(() => {
            clearInterval(t);
          });
        }
      }, 3000);
    }
  }, [hasConn, stores.appStore.clientCfg]);

  return (
    <Provider stores={stores}>
      <BrowserRouter>
        <ConfigProvider locale={zhCN}>
          {hasConn && (
            <ErrorBoundary>
              {renderRoutes(routes)}
            </ErrorBoundary>
          )}
        </ConfigProvider>
      </BrowserRouter>
    </Provider >
  );
};

const root = createRoot(document.getElementById('root')!);
root.render(<App />);

window.addEventListener('unhandledrejection', function (event) {
  // 防止默认处理（例如将错误输出到控制台）
  event.preventDefault();
  if (`${event.reason}`.includes("error trying to connect")) {
    return;
  }
  message.error(event?.reason);
  // console.log(event);
  try {
    report_error({
      err_data: `${event?.reason}`,
    });
  } catch (e) {
    console.log(e);
  }
});
